package com.atguigu.yygh.cmn.service.impl;


import com.alibaba.excel.EasyExcel;
import com.atguigu.yygh.cmn.listener.DictListener;
import com.atguigu.yygh.cmn.mapper.DictMapper;
import com.atguigu.yygh.cmn.service.DictService;
import com.atguigu.yygh.model.cmn.Dict;
import com.atguigu.yygh.vo.cmn.DictEeVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 组织架构表 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2025-03-13
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {
    @Autowired
    private DictMapper dictMapper;
    @Cacheable(value = "dict", key = "'selectIndexList'+#pid")
    @Override
    public List<Dict> getDictListByParentId(Long pid) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", pid);
        List<Dict> dicts = dictMapper.selectList(queryWrapper);
        for (Dict dict : dicts) {
            // 判断是否有子节点

                dict.setHasChildren(hasChild(dict.getId()));

        }
        return dicts;
    }
    //excel导出
    @Override
    public void exportDict(HttpServletResponse response) throws Exception {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("数据字典", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");
        List<Dict> dicts = dictMapper.selectList(null);
        List<DictEeVo> dictEeVos = new ArrayList<>();
        dicts.forEach(dict -> {
            DictEeVo dictEeVo = new DictEeVo();
            BeanUtils.copyProperties(dict,dictEeVo);
            dictEeVos.add(dictEeVo);
        });
        EasyExcel.write(response.getOutputStream(), DictEeVo.class)
                .sheet("数据字典").doWrite(dictEeVos);

    }
    //excel导入
    @Override
    public void importDict(MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(),DictEeVo.class,new DictListener(dictMapper))
                .sheet(0).doRead();
    }

    @Override
    public String getName(String parentDictCode, String value) {
        if (StringUtils.isEmpty(parentDictCode)){
            Dict dict = dictMapper.selectOne(new QueryWrapper<Dict>().eq("value", value));
            if (dict!= null){
                return dict.getName();
            }
        }else{
            Dict dict=this.getDictByDictCode(parentDictCode);
            if (dict!= null){
                QueryWrapper<Dict> queryWrapper = new QueryWrapper<Dict>()
                        .eq("parent_id", dict.getId())
                        .eq("value", value);
                Dict dict1 = dictMapper.selectOne(queryWrapper);
                return dict1.getName();
            }
            return "";
        }
        return "";
    }

    @Override
    public List<Dict> getDictListByDictCode(String dictCode) {
        //根据dictcode查询id作为parent_id查询
        Dict byDictCode = getDictByDictCode(dictCode);
        if (byDictCode!= null){
            return getDictListByParentId(byDictCode.getId());
        }
        return null;
    }

    private Dict getDictByDictCode(String parentDictCode) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<Dict>().eq("dict_code", parentDictCode);
        Dict dict = dictMapper.selectOne(queryWrapper);
        return dict;
    }

    public Boolean hasChild(Long id) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", id);
        Integer i = dictMapper.selectCount(queryWrapper);
        return i>0;
    }

}
